import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
        
/**
 *
 * @author Andy
 */
public class FriendPanel extends javax.swing.JPanel {
    private Controller controls;
    private String type;
    private DatabaseConnection dbConnect;
    /**
        Creates new form FriendPanel
    **/
    public FriendPanel(Controller control, DatabaseConnection db) {
        this.controls = control;
        this.dbConnect = db;
        this.type = "friend";
        initComponents();
        this.setProfilePicture("src/empty_profile_picture.gif");
    }
    
    /**
        Sets the image of this friend panel
    **/
    public void setProfilePicture(String imageName) {
        try {
            BufferedImage image = ImageIO.read(new File(imageName));
            Image scaledImage = image.getScaledInstance(
                    85, 84, Image.SCALE_DEFAULT
            );
            ImageIcon imageIcon = new ImageIcon(scaledImage);
            this.profilePictureLabel.setIcon(imageIcon);
        }
        catch (IOException e) {
            System.err.println("problem reading in image: " + imageName);
        }
    }
    
    /**
        Hides the profile viewing button and makes the 
        functionality of this panel solely for making friend requests
    **/
    public void notFriend() {
        this.playButton.setText("Add Friend");
        this.type = "not friend";
    }
    
    /**
        Makes the buttons for these panels act as deny and accept buttons
        * for a friend request
    **/
    public void friendRequest() {
        this.viewProfileButton.setVisible(true);
        this.viewProfileButton.setText("Accept");
        this.playButton.setText("Deny");
        this.type = "request";
    }
    
    /**
       Sets the username of this panel
    **/
    public void setUsername(String username) {
        this.usernameLabel.setText(username);
    }
    
    /**
       Sets the username of this panel
    **/
    public void setEmail(String email) {
        this.emailLabel.setText(email);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        profilePictureLabel = new javax.swing.JLabel();
        usernameLabel = new javax.swing.JLabel();
        emailLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        playButton = new javax.swing.JButton();
        viewProfileButton = new javax.swing.JButton();

        setBackground(new java.awt.Color(249, 249, 252));
        setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        jPanel1.setBackground(new java.awt.Color(0, 102, 153));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 332, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 37, Short.MAX_VALUE)
        );

        jPanel3.setBackground(new java.awt.Color(249, 249, 252));

        profilePictureLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/empty_profile_picture.gif"))); // NOI18N
        profilePictureLabel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        usernameLabel.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        usernameLabel.setText("Username");

        emailLabel.setText("Email");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(profilePictureLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(emailLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                    .addComponent(usernameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(emailLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(profilePictureLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(75, 75, 75))
        );

        jPanel2.setBackground(new java.awt.Color(0, 102, 153));

        playButton.setText("Play!");
        playButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        viewProfileButton.setText("View Profile");
        viewProfileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewProfileButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(168, Short.MAX_VALUE)
                .addComponent(viewProfileButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(playButton)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(12, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(playButton)
                    .addComponent(viewProfileButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed
        // start a new game
        if(type.equals("friend"))
            this.controls.openGame(usernameLabel.getText());
        else if(type.equals("not friend")){
            // user requests other as a friend
            dbConnect.connect();
            String friendRequestQuery = String.format(
                    "INSERT INTO friend_request VALUES('%s', '%s')",
                    this.controls.username, this.usernameLabel.getText()
            );
            int result = dbConnect.executeUpdate(friendRequestQuery);
            if (result > -1) {
                this.playButton.setEnabled(false);
            }
            dbConnect.closeConnection();
        }
        else if(type.equals("request")){
            // user denies the friend request
            dbConnect.connect();
                
            String denyUpdate = String.format(
                    "DELETE FROM friend_request WHERE user1='%s' AND user_requested='%s'",
                    this.usernameLabel.getText(), this.controls.username
            );
                
            int resultDeny = dbConnect.executeUpdate(denyUpdate);
            if (resultDeny > -1) {
                this.controls.friendsList.deletePanel(this);
            }
                
            dbConnect.closeConnection();
        }
    }//GEN-LAST:event_playButtonActionPerformed

    private void viewProfileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewProfileButtonActionPerformed

        if(type.equals("friend") || type.equals("not friend"))
                this.controls.openFriendProfile(this.usernameLabel.getText());
        else if(type.equals("request")){
            dbConnect.connect();

            String acceptInsert = String.format(
                "INSERT INTO friends VALUES('%s', '%s')",
                this.controls.username, this.usernameLabel.getText()
            );

            System.out.println(acceptInsert);

            int resultInsertOne = dbConnect.executeUpdate(acceptInsert);

            if (resultInsertOne > -1) {
                acceptInsert = String.format(
                    "INSERT INTO friends VALUES('%s', '%s')",
                    this.usernameLabel.getText(), this.controls.username
                );

                int resultInsertTwo = dbConnect.executeUpdate(acceptInsert);
                if (resultInsertTwo > -1) {
                    // delete friend request as they are now officially friends
                    String acceptDelete = String.format(
                            "DELETE FROM friend_request WHERE user1='%s' AND user_requested='%s'",
                            this.usernameLabel.getText(), this.controls.username
                    );

                    int resultDelete = dbConnect.executeUpdate(acceptDelete);
                    if (resultDelete > -1) {
                        this.controls.friendsList.deletePanel(this);
                    }
                }
                else {
                    // maintain the friend request for another try
                    String acceptDelete = String.format(
                            "DELETE FROM friends WHERE user1='%s' AND user2='%s'",
                            this.controls.username, this.usernameLabel.getText()
                    );

                    dbConnect.executeUpdate(acceptDelete);
                }
            }

            dbConnect.closeConnection();
        }
    }//GEN-LAST:event_viewProfileButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel emailLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton playButton;
    private javax.swing.JLabel profilePictureLabel;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JButton viewProfileButton;
    // End of variables declaration//GEN-END:variables
}
